package com.watermeter.android.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.oa.android.R;
import com.watermeter.android.adapter.RouteItemAdapter;
import com.watermeter.android.entry.DownRoute;
import com.watermeter.android.entry.Rows;
import com.zxing.android.CaptureActivity;

import org.w3c.dom.Text;
import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;


/**
 * 待抄表列表
 *
 * @author -zouqh
 */
public class SeachActivity extends Activity implements OnClickListener {

    private ImageView close, scan;
    private TextView title,sureSelect;
    private ListView listView;
    private EditText editText;
    private RouteItemAdapter adapter;
    private List<DownRoute> downRoutelist;
    public List<DownRoute> downRoutelist1;
    public DbManager.DaoConfig daoConfig;
    private String routeId;
    public int flag = 0;//判断是否保存成功，成功后需要刷新界面
    public int pageSize = 20;
    public int page = 1;
    private long allPage;
    public static SeachActivity activity;
    private String string;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        activity = this;
        setContentView(R.layout.search_cb_activity);
        close = (ImageView) findViewById(R.id.close);
        scan = (ImageView) findViewById(R.id.ritgh_icon);
        title = (TextView) findViewById(R.id.title_text);
        listView = (ListView) findViewById(R.id.listview);
        editText = (EditText) findViewById(R.id.searchCru);
        sureSelect   = (TextView) findViewById(R.id.sureSelect);
//        scan.setImageResource(R.drawable.homepage_scan);
//        moth=getIntent().getStringExtra("moth");
//        listView.setPullLoadEnable(false);// 向上滑动加载更多开启
//        listView.setPullRefreshEnable(false);
//        listView.setXListViewListener(this);
//        scan.setVisibility(View.VISIBLE);
        scan.setOnClickListener(this);
        sureSelect.setOnClickListener(this);
        title.setText("搜索");
        close.setOnClickListener(this);
//



    }

    @Override
    protected void onResume() {
        super.onResume();
//        if (flag != 0) {
//            flag = 0;
//            DcbActivity.dcbActivity.isFlash = 1;
//            getdownDate();
//            adapter.notifyDataSetChanged();
//            getScbNmu();
//        }
        if (null!=downRoutelist1&&downRoutelist1.size()>0){
            getdownDate();
            if (null != downRoutelist && downRoutelist.size() > 0) {
                allPage = (int) Math.ceil((double) downRoutelist.size() / pageSize);
                downRoutelist1 = new ArrayList<>();
                downRoutelist1.addAll(downRoutelist);

                adapter = new RouteItemAdapter(this, downRoutelist1);
                listView.setAdapter(adapter);


            } else {
//                Toast.makeText(this, "暂时没有数据！", Toast.LENGTH_SHORT).show();
            }
        }

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.close:
                finish();
                break;

            case R.id.ritgh_icon:
                intent.setClass(this, CaptureActivity.class);
                startActivityForResult(intent, 1);
                break;

            case R.id.sureSelect:
                routeId= editText.getText().toString();
                if (TextUtils.isEmpty(routeId)){
                    Toast.makeText(this,"请输入客户编号",Toast.LENGTH_SHORT).show();
                    return;
                }

                getdownDate();
                if (null != downRoutelist && downRoutelist.size() > 0) {
                    allPage = (int) Math.ceil((double) downRoutelist.size() / pageSize);
                    downRoutelist1 = new ArrayList<>();
                    downRoutelist1.addAll(downRoutelist);

                    adapter = new RouteItemAdapter(this, downRoutelist1);
                    listView.setAdapter(adapter);


                } else {
                    downRoutelist1.clear();
                    adapter.notifyDataSetChanged();
                    Toast.makeText(this, "暂时没有数据！", Toast.LENGTH_SHORT).show();
                }
                break;

            default:
                break;
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (page<allPage){
                        page++;
                        if(page==allPage){
                            for (int i = page*pageSize; i < downRoutelist.size(); i++) {
                                downRoutelist1.add(downRoutelist.get(i));
                            }
                        }else{
                            for (int i = page*pageSize; i < page*pageSize+pageSize; i++) {
                                downRoutelist1.add(downRoutelist.get(i));
                            }
                        }
//                        onLoad();
                        adapter.notifyDataSetChanged();

                    }else {
//                        listView.setFooterName("", false);

                    }

                    break;

            }

        }
    };


    /**
     * 获取已经下载的路线
     */
    private void getdownDate() {
//
        DbManager manager = x.getDb(daoConfig);
        try {

            downRoutelist = manager.selector(DownRoute.class).where("USERID", "=", routeId).findAll();
            System.out.println(downRoutelist);

        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    private void selectName(String str) {

        downRoutelist1.clear();
        for (int i = 0; i < downRoutelist.size(); i++) {
            if (downRoutelist.get(i).getUSERNAME().contains(str) || downRoutelist.get(i).getUSERID().contains(str)) {
                downRoutelist1.add(downRoutelist.get(i));
            }
        }
        adapter.notifyDataSetChanged();

    }


    /**
     * 获取实抄表条数
     */
    private void getScbNmu() {
//
        DbManager manager = x.getDb(daoConfig);
        long num = 0;
        try {
            if (routeId != null && routeId.length() > 0) {
                num = manager.selector(DownRoute.class).
                        where("CBLINE", "=", routeId).and("change", "=", 1).count();
                System.out.println("num==========" + num);
                List<Rows> rowsList = manager.selector(Rows.class).where("ID", "=", routeId).findAll();
                System.out.println("rowsList==========" + rowsList.size());
                for (int i = 0; i < rowsList.size(); i++) {
                    Rows rows = rowsList.get(i);
                    rows.setSCBNUM((int) num);
                    manager.saveOrUpdate(rows);
                }
            }

            if (num > 0) {

            }


        } catch (DbException e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1) {
            if (data != null) {
                if (resultCode == RESULT_OK) {

                    String string = data.getStringExtra("name");
                    Log.i("string--------", string);
                    editText.setText(string + "");
                    selectName(string);

                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

//    @Override
//    public void onRefresh() {
//
//    }
//
//    @Override
//    public void onLoadMore() {
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    Thread.sleep(1000);
//                    handler.sendEmptyMessage(1);
//
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//        }).start();
//    }
//
//    private void onLoad() {
//        listView.stopRefresh();
//        listView.stopLoadMore();
//        listView.setRefreshTime("刚刚");
//    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        activity = null;
    }
}
